package me.zhengjie.request;

import me.zhengjie.constant.ConstantUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
public final class ContextAssembler {

    /**
     * 从请求头组装Context上下文
     *
     * @param req ServletRequest
     */
    public static void assembleBusContext(ServletRequest req) {
        ATMRContext.init();
        HttpServletRequest request = (HttpServletRequest) req;
        assembleWxReq(request);
    }

    /**
     * 组件微信渠道（公众号、小程序）的参数
     *
     * @param req
     */
    private static void assembleWxReq(HttpServletRequest req) {
        String openId = getDefaultValueIfNull(req.getParameter(ConstantUtils.HEAD_OPEN_ID),
                req.getHeader(ConstantUtils.HEAD_OPEN_ID));
        if (StringUtils.isNotBlank(openId)) {
            ATMRContext.getContext().setOpenId(openId);
        }
    }

    /**
     * @param sourceValue
     * @param defaultValue
     * @return
     */
    private static String getDefaultValueIfNull(String sourceValue, String defaultValue) {
        if (StringUtils.isBlank(sourceValue)) {
            return defaultValue;
        }
        return sourceValue;
    }
}
